from qturboframe.lib.utils.by import By
from qturboframe.lib.webdriver.exceptions import SeleniumError
from qturboframe.lib.report.log import logger

from .base_element import BaseElement


class InputType(BaseElement):
    '''
    Jres2.0文本框操作

    :Attributes:
     - _driver: 控件所在的当前webdriver对象
     - _element: 控件元素webelement对象
     - timeout: 步骤操作的超时时间

    :Example:
     - 例1: InputType(webelement)
     - 例2: InputType('登录')
     - 例3: InputType({By.NAME:'name'})
     - 例4: InputType({By.CLASS_NAME:'class_name','text':'文本信息'})
     - 例5: InputType({By.CLASS_NAME:'class_name','text':'文本信息'}, father=driver)
     - 例6: InputType({By.CLASS_NAME:'class_name','text':'文本信息'}, father=webelement)
    '''
    
    def __init__(self, element_para, father=None, timeout=5):
        if isinstance(element_para, str):
            #这个将会被遗弃
            xpath = ".//input[@placeholder='{}']".format(element_para.strip())
            input = father.exist("xpath", xpath, timeout = timeout)
            if input:
                super().__init__(input, father, timeout)
                return 
            raise SeleniumError("没有找到'{}'对应的input框".format(element_para))
        if isinstance(element_para, dict) and By.TEXT in element_para:
            xpath = ".//input[@placeholder='{}']".format(element_para.get(By.TEXT).strip())
            input = father.exist("xpath", xpath, timeout = timeout)
            if input:
                super().__init__(input, father, timeout)
                return
            raise SeleniumError("没有找到'{}'对应的input框".format(element_para))
        elif isinstance(element_para, list):
            self._elements = element_para
            self._driver = element_para[0]._parent
            self.timeout = timeout
        else:
            super().__init__(element_para, father, timeout)

    def set_value(self, value):
        '''
        Jres2.0文本框填充

        :Args:
         - text: 填充值

        :Example:
         - 例: input_type.set_value("12345")
        '''
        self._element.focus()
        self._element.clear()
        self._element.send_keys(value)

    def is_readonly(self):
        '''
        Jres2.0检查文本框是否只读

        :Return:
            返回文本框是否只读

        :Example:
         - 例: input_type.is_readonly()
        '''
        self._element.focus()
        return self._element.is_readonly()

    def clear(self):
        '''
        Jres2.0文本框清空

        :Example:
         - 例: input_type.clear()
        '''
        self._element.focus()
        self._element.clear()

    @staticmethod
    def is_readonly_for_group(self, inputs):
        """
        jres2.0的文本框组只读校验是否成功

        :Args:
         - inputs: 文本框控件组

        :Returns:
            控件组均是只读状态则返回True，否则返回False

        :Example:
         - 例: input_type.is_readonly_for_group(inputs)
        """
        for inputele in inputs:
            if not inputele.is_readonly():
                return False
        else:
            return True

    @staticmethod
    def is_default_for_group(self, inputs, value):
        """
        检查jres2.0的文本框组默认值

        :Args:
         - inputs: 文本框控件组
         - value: 待检查的一组值

        :Returns:
            检查所有都匹配返回True，否则返回False

        :Example:
         - 例: input_type.is_default_for_group(inputs)
        """
        re_typefield = r'u-typefield'
        value1 = value[0]
        if len(value) < 2:
            value2 = value[0]
        else:
            value2 = value[1]
        textlist = list()
        for inputele in inputs:
            if inputele.text:
                textlist.append(inputele.text)
            elif inputele.get_attribute('value'):
                textlist.append(inputele.get_attribute('value'))
            elif inputele.get_attribute('placeholder'):
                textlist.append(inputele.get_attribute('placeholder'))
            elif inputele.get_attribute('title'):
                textlist.append(inputele.get_attribute('title'))
            else:
                textlist.append("")
        for i in range(0,len(inputs)):
            if re_typefield in inputs[i].get_attribute('class'):
                textlist[i] = textlist[i].replace(',','')
        if textlist[0] == value1 and textlist[1] == value2:
            return True
        else:
            logger.error('文本框组默认值与校验值不一致！')
            return False